package com.thy.axq.action;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import com.cmos.core.bean.InputObject;
import com.cmos.core.util.JsonUtil;

public class ActiveMqPrvoderClient {

	public void AxMsgSend(InputObject input, String axName, int msgLevel) throws JMSException {
		Connection connection = null;
		Session session = null;
		try {
			// 从连接池工厂中获取一个连接
			connection = ActiveMqConnClient.getActiveMQConnectionFactory().createConnection();
			// 必须start，否则无法接收消息
			connection.start();
			// false 参数表示 为非事务型消息，后面的参数表示消息的确认类型
			session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
			// PTP消息方式
			Destination destination = session.createQueue(axName);
			// Creates a MessageProducer to send messages to the specified
			// destination
			MessageProducer producer = session.createProducer(destination);
			// set delevery mode
			producer.setDeliveryMode(DeliveryMode.PERSISTENT);
			// 消息优先级
			producer.setPriority(msgLevel);
			// map convert to javax message
			Message message = getMessage(session, input);
			producer.send(message);
			// 提交会话
			session.commit();
			// 使用完必须要关闭，否则消息会被阻塞，无法发送出去
			closeSession(session);
			closeConnection(connection);
		} finally {
			if (null != session) {
				closeSession(session);
			}
			if (null != connection) {
				closeConnection(connection);
			}
		}
	}


	private void closeSession(Session session) {
		try {
			if (session != null) {
				session.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void closeConnection(Connection connection) {
		try {
			if (connection != null) {
				connection.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private Message getMessage(Session session, InputObject inputObject) throws JMSException {
		ObjectMessage message = session.createObjectMessage(JsonUtil.convertObject2Json(inputObject));
		return message;
	}
}
